package com.example.standard.service;

import com.example.standard.entity.Standard;
import com.example.standard.repository.StandardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class StandardService {
    @Autowired
    StandardRepository standardRepository;

    public Page<Standard> search(String name, int indexPage) {
        Pageable pageable = PageRequest.of(indexPage - 1, 2);
        return standardRepository.findAll(new Specification<Standard>() {
            @Override
            public Predicate toPredicate(Root<Standard> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                // 根据条件是否为空动态拼接条件
                List<Predicate> predicates = new ArrayList<>();
                if (!(name == null || name == "")) {
                    predicates.add(criteriaBuilder.like(root.get("zhname"), name));
                }
                query.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
                // 指定排序
                query.orderBy(criteriaBuilder.asc(root.get("name")));
                return query.getRestriction();
            }
        }, pageable);
    }

    //修改
    @Transactional
    public void update(String name,String zhname,String version,String keys,String ksdate,String jsdate,String path, int id) {
        standardRepository.updateStatus(name,zhname,version,keys,ksdate,jsdate,path,id);
    }
    //根据id查询
    public Standard selectID(Integer id){
        return standardRepository.findById(id).get();
    }

    //新增
    public int insert(String name, String zhname, String version, String keys, String ksdate, String jsdate, String path) {
        standardRepository.finsdafdsad(name, zhname, version, keys, ksdate, jsdate, path);
        return 1;
    }

    public int count(String name) {
        return standardRepository.countByName(name);
    }
    public int delete(int [] id){
        for (int i : id) {
            standardRepository.deleteById(i);
        }
        return  1;
    }



}
